package com.yy.weixinpay.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.yy.weixinpay.entity.OrderInfo;
import com.yy.weixinpay.entity.RefundInfo;
import com.yy.weixinpay.enums.wxpay.AliPayTradeState;
import com.yy.weixinpay.mapper.RefundInfoMapper;
import com.yy.weixinpay.service.OrderInfoService;
import com.yy.weixinpay.service.RefundInfoService;
import com.yy.weixinpay.utils.OrderNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoMapper, RefundInfo> implements RefundInfoService {
    @Autowired
    private OrderInfoService orderInfoService;
    @Override
    public RefundInfo createRefundByOrderNo(String orderNo,String reason) {
        //查询订单信息
        OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderNo);
        //根据订单生成退款订单
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setOrderNo(orderNo);
        refundInfo.setRefundNo(OrderNoUtils.getRefundNo());
        refundInfo.setTotalFee(orderInfo.getTotalFee());
        refundInfo.setRefund(orderInfo.getTotalFee());
        refundInfo.setReason(reason);
        baseMapper.insert(refundInfo);
        return refundInfo;
    }

    /**
     * 更新退款单
     * @param s
     */
    @Override
    public void updateRefund(String s) {
        Gson gson = new Gson();
        Map<String,Object> map = gson.fromJson(s, Map.class);
        //根据退款单来修改退款数据
        QueryWrapper<RefundInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_no",map.get("out_refund_no"));

        //设置要修改的字段
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setRefundId((String) map.get("refund_id"));
        //查询退款和申请退款中的返回参数
        if ((String)map.get("status") != null){
            refundInfo.setRefundStatus((String) map.get("status"));
            refundInfo.setContentReturn(s);
        }
        //退款回调中的回调参数
        if ((String)map.get("refund_status") != null){
            refundInfo.setRefundStatus((String) map.get("refund_status"));
            refundInfo.setContentNotify(s);
        }

        //更新退款单子
        baseMapper.update(refundInfo,queryWrapper);
    }

    /**
     * 更新呢支付宝退款的退款单
     * @param refundNo
     * @param body
     * @param refundStatus
     */
    @Override
    public void updateRefundForAliPay(String refundNo, String body, String refundStatus) {
        //根据退款单号来修改
        QueryWrapper<RefundInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_no",refundNo);
        //设置要修改的字段
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setRefundStatus(refundStatus);
        refundInfo.setContentReturn(body);
        baseMapper.update(refundInfo,queryWrapper);
    }
}
